package app.modules.cloudpivot.service.impl;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.authine.cloudpivot.engine.api.facade.UserFacade;
import com.authine.cloudpivot.engine.api.model.dto.MessageDTO;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.service.message.ISmsService;

import darabonba.core.client.ClientOverrideConfiguration;

/**
 * 阿里云短信服务
 *
 * @author LiuGangQiang Create in 2023/02/28
 */
@Service
public class CustomSmsServiceImpl implements ISmsService {
    private static final Logger log = LoggerFactory.getLogger(CustomSmsServiceImpl.class);

    @Value("${aliyun.sms.region}")
    private String region;
    @Value("${aliyun.sms.sign}")
    private String sign;
    @Value("${aliyun.sms.accesskey.id}")
    private String accessKeyId;
    @Value("${aliyun.sms.accesskey.secret}")
    private String accessKeySecret;
    @Value("${aliyun.sms.verification.code.template:SMS_154950909}")
    private String verificationCodeTemplate;
    @Value("${aliyun.sms.verification.code.key:code}")
    private String verificationCodeKey;

    @Resource
    private UserFacade userFacade;

    @Override
    public String doSendSms(MessageDTO message) {
        /* 构造签名 */
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                .build());

        /* 构造异步客户端 */
        AsyncClient client = AsyncClient.builder()
                .region(region)
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("dysmsapi.aliyuncs.com"))
                .build();

        /* 获取用户 */
        UserModel user = userFacade.get(message.getReceivers());

        /* 构造发送信息 */
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(sign)
                .phoneNumbers(user.getMobile())
                .templateCode(message.getSmsCode())
                .templateParam(message.getSmsParams())
                .build();

        /* 异步发送短信 */
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp;
        try {
            resp = response.get();
            if ("OK".equals(resp.getBody().getCode())) {
                log.info("===>>短信发送成功，目标手机号码：{}，签名：{}，短信内容：{}，短信参数：{}", user.getMobile(), sign, message.getContent(), message.getSmsParams());
                return "1";
            } else {
                log.info("===>>短信发送失败，目标手机号码：{}，签名：{}，短信内容：{}，短信参数：{}，错误信息：{}", user.getMobile(), sign, message.getContent(), message.getSmsParams(), JSONObject
                        .toJSONString(resp.getBody()));
                return "-1";
            }
        } catch (InterruptedException | ExecutionException e) {
            log.warn("===>>发送短信出现异常,异常信息：{}", e.getMessage());
            return "-1";
        } finally {
            client.close();
        }
    }

    @Override
    public boolean sendVerificationCode(String mobile, String code) {
        /* 构造签名 */
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                .build());

        /* 构造异步客户端 */
        AsyncClient client = AsyncClient.builder()
                .region(region)
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("dysmsapi.aliyuncs.com"))
                .build();

        /* 构造发送信息 */
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(sign)
                .phoneNumbers(mobile)
                .templateCode(verificationCodeTemplate)
                .templateParam("{\"" + verificationCodeKey + "\":\"" + code + "\"}")
                .build();

        /* 异步发送短信 */
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp;
        try {
            resp = response.get();
            if ("OK".equals(resp.getBody().getCode())) {
                log.info("===>>验证码发送成功，目标手机号码：{}，签名：{}，验证码：{}", mobile, sign, code);
                return true;
            } else {
                log.info("===>>验证码发送失败，目标手机号码：{}，签名：{}，验证码：{}，错误信息：{}", mobile, sign, code, JSONObject.toJSONString(resp.getBody()));
                return false;
            }
        } catch (InterruptedException | ExecutionException e) {
            log.warn("===>>发送短信验证码出现异常,异常信息：{}", e.getMessage());
            return false;
        } finally {
            client.close();
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        /* 构造签名 */
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("LTAI5tKL9Gf9UkTANWBc7wVQ")
                .accessKeySecret("J90qQ5l5FMbA14LOLn0giH0ch2h66O")
                .build());

        /* 构造异步客户端 */
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou")
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("dysmsapi.aliyuncs.com"))
                .build();

        /* 构造发送信息 */
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("阿里云短信测试")
                .phoneNumbers("19150303251")
                .templateCode("SMS_154950909")
                .templateParam("{\"code\":\"123456\"}")
                .build();

        /* 异步发送短信 */
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = response.get();
        System.out.println(resp.getBody().getMessage());
    }
}
